package com.mt.mall.service.Mq;

import com.alibaba.fastjson.JSONObject;
import com.mt.common.core.config.RabbitMqConfig;
import com.mt.common.core.security.RedisUtil;
import com.mt.common.core.utils.ESUtil;
import com.mt.mall.dao.Order.OrderDao;
import com.mt.mall.entity.Order.Order;
import com.mt.mall.entity.good.Commodity;
import com.mt.mall.service.good.CommodityService;
import com.mt.mall.service.good.SpecificationStockService;
import com.mt.mall.service.skill.SkillCommodityService;
import com.rabbitmq.client.Channel;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

/**
 * @ClassName: OrderTimeOutService
 * @Description:
 * @Author zhanghong
 * @Date 2022/5/16
 */
@Component
@Transactional
@RabbitListener(queues = {RabbitMqConfig.DLX_QUEUE})
public class OrderTimeOutServiceImpl  {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private SpecificationStockService specificationStockService;
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SkillCommodityService skillCommodityService;

    @Autowired
    private ESUtil esUtil;
    private String INDEX_NAME = "commodity";
    @Autowired
    private CommodityService commodityService;

    private Logger logger= LoggerFactory.getLogger(OrderTimeOutServiceImpl.class);

    @RabbitHandler
    public void handleTtlOrder(Order order) throws IOException {
        try{
            //Order order= JSONObject.toJavaObject(JSONObject.parseObject(message),Order.class);//订单超时逻辑处理
            Integer row=this.orderDao.orderTimedOutUpdate(order.getEid());
            //如果订单更新成功，说明未付款,为超时取消
            if(row==1){
                //普通订单
                if(order.getSkillCommodityId()==null) {
                    //1、更新数据库库存
                    this.specificationStockService.incrStock(order.getCommodityId(), order.getSpecification(), order.getCount());
                    //2、删除缓存还是直接更新缓存（考虑）
                    String key=order.getCommodityId() + "-" + order.getSpecification();
                    redisUtil.incr(key,order.getCount());

                }
                //秒杀订单
                else {
                    this.skillCommodityService.incrStock(order.getSkillCommodityId(),1);
                    //删除缓存
                    //redisUtil.del("skill-"+order.getCommodityId()+"-"+order.getSpecification());
                    //更新缓存
                    String key="skill-"+order.getCommodityId()+"-"+order.getSpecification();
                    redisUtil.decr(key,1);
                }
                logger.info(order.toString()+"超时取消");
            }else{
                //销量增加
                this.commodityService.updateCommoditySaleNum(order.getCommodityId(),order.getCount());
                //es
                Commodity commodity = esUtil.selectDocumentById(INDEX_NAME, String.valueOf(order.getCommodityId()), Commodity.class);
                commodity.setSaleNum(commodity.getSaleNum()+order.getCount());
                esUtil.insertDocument(INDEX_NAME,commodity);
            }

            /**
             * 确认一条消息：<br>
             * channel.basicAck(deliveryTag, false); <br>
             * deliveryTag:该消息的index <br>
             * multiple：是否批量.true:将一次性ack所有小于deliveryTag的消息 <br>
             */
            //channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            logger.info("消息应答成功");
        }catch (Exception e){
            //消费者处理出了问题，需要告诉队列信息消费失败
            //channel.basicNack(message.getMessageProperties().getDeliveryTag(),
            //        false, true);
            logger.error("消息应答失败");
        }

    }
}
